/*
 * CheckSecurityConstrainsFilter.java
 *
 * Created on 15 luty 2007, 14:30
 *
 */

package arocms.security;

import arocms.Constans;
import java.io.IOException;
import java.util.Iterator;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import arocms.security.SecurityService.Permission;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author arek
 */
public class CheckSecurityConstrainsFilter implements Filter{
    
    private static SecurityService sservice;
    
    /** Creates a new instance of CheckSecurityConstrainsFilter */
    public CheckSecurityConstrainsFilter() {
    }
    
    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            sservice = SecurityServiceFactory.configure();
        } catch (SecurityServiceConfigurationException ex) {
            ServletException ex2 = new ServletException();
            ex2.setStackTrace(ex.getStackTrace());
            throw ex2;
        }
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        try {
            SecurityService sservice = SecurityServiceFactory.configure();
            String uri = req.getRequestURI();
            String context = req.getContextPath();
            String turi = uri.substring(context.length(), uri.length());
            Role roles = (Role) req.getSession(true).getAttribute(Constans.ROLE_PATH);
            Permission p = sservice.checkAccess(turi, roles);
            
            if (p == p.ALLOWED) chain.doFilter(req,response);
            else {
                ((HttpServletResponse) response).sendError(403);
            }
           
        } catch (SecurityServiceConfigurationException ex) {
            ServletException ex2 = new ServletException();
            ex2.setStackTrace(ex.getStackTrace());
            throw ex2;
        }
    }
    
    public void destroy() {
    }
    
}
